package com.cykj.pos.controller.TestDTO;

import com.cykj.common.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * @author xuxiya on 2018/3/21.
 */
public class HttpClientHandler {

    public static String onRequest(String postUrl, Map<String, String> parameter, Map<String, FileItem> fileItemMap) {
        String respResult = null;
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            RequestConfig.Builder reqConfigBuilder = RequestConfig.custom();
            reqConfigBuilder.setSocketTimeout(90000);
            reqConfigBuilder.setConnectTimeout(90000);
            reqConfigBuilder.setConnectionRequestTimeout(90000);
            RequestConfig reqConfig = reqConfigBuilder.build();
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            CloseableHttpClient httpClient = httpClientBuilder.build();
            String boundary = generateBoundary();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary("-------------" + boundary).setMode(HttpMultipartMode.RFC6532);

            if (parameter != null && !parameter.isEmpty()) {
                for (Map.Entry<String, String> entry : parameter.entrySet()) {
                    if (StringUtils.isNotBlank(entry.getValue())) {
                        builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("multipart/form-data", "UTF-8"));
                    }
                }
            }

            if (fileItemMap != null && !fileItemMap.isEmpty()) {
                for (Map.Entry<String, FileItem> entry : fileItemMap.entrySet()) {
                    FileItem fileItem = entry.getValue();
                    if (StringUtils.isNotBlank(entry.getKey()) && fileItem != null) {
                        builder.addBinaryBody(entry.getKey(), fileItem.getFile(), ContentType.create("multipart/form-data", "UTF-8"), fileItem.getFileName());
                    }
                }
            }
            HttpEntity httpEntity = builder.build();
            HttpPost httpPost = new HttpPost(postUrl);
            httpPost.setHeader("Content-Type", "multipart/form-data;charset=utf-8;boundary=-------------" + boundary);
            httpPost.setEntity(httpEntity);
            HttpResponse resp = httpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httEntity = resp.getEntity();
                respResult = EntityUtils.toString(httEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return respResult;
    }
    public static String noPictureRequest(String postUrl, Map<String, String> parameter) {
        String respResult = null;
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            RequestConfig.Builder reqConfigBuilder = RequestConfig.custom();
            reqConfigBuilder.setSocketTimeout(90000);
            reqConfigBuilder.setConnectTimeout(90000);
            reqConfigBuilder.setConnectionRequestTimeout(90000);
            RequestConfig reqConfig = reqConfigBuilder.build();
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            CloseableHttpClient httpClient = httpClientBuilder.build();
            String boundary = generateBoundary();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary("-------------" + boundary).setMode(HttpMultipartMode.RFC6532);

            if (parameter != null && !parameter.isEmpty()) {
                for (Map.Entry<String, String> entry : parameter.entrySet()) {
                    if (StringUtils.isNotBlank(entry.getValue())) {
                        builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.create("multipart/form-data", "UTF-8"));
                    }
                }
            }
            HttpEntity httpEntity = builder.build();
            HttpPost httpPost = new HttpPost(postUrl);
            httpPost.setHeader("Content-Type", "multipart/form-data;charset=utf-8;boundary=-------------" + boundary);
            httpPost.setEntity(httpEntity);
            HttpResponse resp = httpClient.execute(httpPost);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httEntity = resp.getEntity();
                respResult = EntityUtils.toString(httEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return respResult;
    }
    public static String onRequests(String strEntity, String postUrl, String contentType) {
        String respResult = null;
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            RequestConfig.Builder reqConfigBuilder = RequestConfig.custom();
            reqConfigBuilder.setSocketTimeout(60000);
            reqConfigBuilder.setConnectTimeout(60000);
            reqConfigBuilder.setConnectionRequestTimeout(60000);
            RequestConfig reqConfig = reqConfigBuilder.build();
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            HttpClient client = httpClientBuilder.build();
            HttpPost httPost = new HttpPost(postUrl);
            String charset = "UTF-8";
            StringEntity entity = new StringEntity(strEntity, charset);
            entity.setContentEncoding(charset);
            entity.setContentType(contentType);
            httPost.setEntity(entity);
            HttpResponse resp = client.execute(httPost);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httEntity = resp.getEntity();
                respResult = EntityUtils.toString(httEntity);
            }
            HttpClientUtils.closeQuietly(client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respResult;
    }



    public static String onRequestGet(String postUrl) {
        String respResult = null;
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            RequestConfig.Builder reqConfigBuilder = RequestConfig.custom();
            reqConfigBuilder.setSocketTimeout(6000);
            reqConfigBuilder.setConnectTimeout(3000);
            reqConfigBuilder.setConnectionRequestTimeout(3000);
            RequestConfig reqConfig = reqConfigBuilder.build();
            httpClientBuilder.setDefaultRequestConfig(reqConfig);
            HttpClient client = httpClientBuilder.build();
            HttpGet httGet = new HttpGet(postUrl);
            HttpResponse resp = client.execute(httGet);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httEntity = resp.getEntity();
                respResult = EntityUtils.toString(httEntity);
            }
            HttpClientUtils.closeQuietly(client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respResult;
    }

    private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    private static String generateBoundary() {
        final StringBuilder buffer = new StringBuilder();
        final Random rand = new Random();
        // a random size from 30 to 40
        final int count = rand.nextInt(11) + 30;
        for (int i = 0; i < count; i++) {
            buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        return buffer.toString();
    }
}
